package com.codeoss.framework.view.parser;

import org.springframework.stereotype.Service;

import com.codeoss.framework.expression.Expression;
import com.codeoss.framework.expression.ExpressionUtil;
import com.codeoss.framework.util.StringUtils;
import com.codeoss.framework.view.component.Component;
import com.codeoss.framework.view.component.Tree;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

@Service
public class TreeParser extends AbstractComponentParser {
	protected void setAttributes(IParseContext parseContext, ObjectNode objectNode, Component component) {
		super.setAttributes(parseContext, objectNode, component);
		Tree tree = (Tree) component;
		ObjectNode propertyMapNode = (ObjectNode) objectNode.get("propertyMap");
		if (propertyMapNode != null) {
			JsonNode jsonNode = propertyMapNode.get("dataSource");
			if (jsonNode != null) {
				String dataSource = propertyMapNode.get("dataSource").asText();
				tree.setDataSource(dataSource);
			}
			jsonNode = propertyMapNode.get("varName");
			if(jsonNode!=null) {
				String varName = propertyMapNode.get("varName").asText();
				tree.setVarName(varName);
			}
			jsonNode=propertyMapNode.get("onItemClickExpression");
			if(jsonNode!=null) {
				String onItemClickExpression=jsonNode.asText();
				if(!StringUtils.isEmpty(onItemClickExpression)) {
					String expressionType=Expression.EXPRESSION_TYPE_JAVASCRIPT;
					if(onItemClickExpression.startsWith("@")) {
						expressionType=Expression.EXPRESSION_TYPE_SPRING;
					}
					Expression expression=ExpressionUtil.convertToExpression(onItemClickExpression,expressionType);
					tree.setOnItemClickExpression(expression);
				}
			}
		}
		JsonNode jsonNode=objectNode.get("checked");
		if(jsonNode!=null) {
			tree.setChecked(jsonNode.asBoolean());
		}
	}

	@Override
	protected Component createComponent(IParseContext parseContext, ObjectNode objectNode) {
		// TODO Auto-generated method stub
		return new Tree();
	}

}
